package com.lujianfei.powersearch.adapter

import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.databinding.ObservableArrayList
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.base.BaseDatabindingAdapter
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.AdapterItemBinding
import com.lujianfei.powersearch.logger.LoggerFactory
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.model.ImageViewEditItem
import com.lujianfei.powersearch.ui.preview.FullScreenPreviewActivity
import com.lujianfei.powersearch.utils.AppJumpUtils
import com.lujianfei.powersearch.utils.ImageUtils
import com.lujianfei.powersearch.utils.SpanUtils
import com.lujianfei.powersearch.utils.SystemUtils

open class CommonAdapter(items: ObservableArrayList<SearchItemModel>) :
    BaseDatabindingAdapter<SearchItemModel, AdapterItemBinding>(items) {

    var onItemClick: ((SearchItemModel) -> Unit)? = null
    var onItemLongClick: ((SearchItemModel) -> Unit)? = null
    var hasPerformLongClick = false
    var hasLinkClick = false
    val TAG = "CommonAdapter"
    val log = LoggerFactory.getLogger()

    override fun getLayoutResId() = R.layout.adapter_item

    override fun onBindItem(binding: AdapterItemBinding?, item: SearchItemModel, position: Int) {
        val mSpanUtils = SpanUtils()
        binding?.rootView?.setOnClickListener {
            performClick(item)
        }
        binding?.txtInfo?.setOnClickListener {
            binding.rootView.performClick()
        }
        binding?.rootView?.setOnLongClickListener {
            hasPerformLongClick = true
            onItemLongClick?.invoke(item)
            true
        }
        binding?.txtInfo?.setOnLongClickListener {
            hasPerformLongClick = true
            onItemLongClick?.invoke(item)
            true
        }
        mSpanUtils.textView(binding?.txtInfo).content(item.name ?: "").addUrl {
            hasLinkClick = true
            if (hasPerformLongClick) {
                hasPerformLongClick = false
                return@addUrl
            }
            AppJumpUtils.startWebLink(context = binding?.txtInfo?.context, it)
        }.addPhone {
            hasLinkClick = true
            if (hasPerformLongClick) {
                hasPerformLongClick = false
                return@addPhone
            }
            AppJumpUtils.startPhone(context = binding?.txtInfo?.context, it)
        }.addAddress {
            hasLinkClick = true
            if (hasPerformLongClick) {
                hasPerformLongClick = false
                return@addAddress
            }
            AppJumpUtils.startMap(context = binding?.txtInfo?.context, it)
        }
        binding?.ivPhoto?.setOnClickListener {
            startPhotoPlayer(SystemUtils.getApplicationContext(), item)
        }
        binding?.showLevel = false
        binding?.btBindApp?.setOnClickListener {
            item.packageName?.let {
                startApp(packageName = it)
            }
        }
        binding?.model = item
        kotlin.runCatching {
            if (item.imagePath.isNullOrBlank()) {
                binding?.photo = null
            } else {
                val imagePathArr = item.imagePath?.split(",")
                if (imagePathArr.isNullOrEmpty()) {
                    log.d(TAG,"item.imagePath=${item.imagePath}")
                    binding?.showPlay = item.imagePath?.contains("video")
                    binding?.photo = ImageUtils.getImageByPath(item.imagePath)
                } else {
                    imagePathArr.first().let { firstPath->
                        log.d(TAG,"firstPath=$firstPath")
                        binding?.showPlay = firstPath.contains("video")
                        binding?.photo = ImageUtils.getImageByPath(firstPath)
                    }
                }
            }
        }.onFailure {
            binding?.photo = null
        }
    }

    private fun performClick(item: SearchItemModel) {
        if (item.id != item.selectId) {
            if (!hasLinkClick) {
                onItemClick?.invoke(item)
            } else {
                hasLinkClick = false
            }
        }
    }

    private fun startPhotoPlayer(context:Context, item:SearchItemModel) {
        item.imagePath?.let {
            FullScreenPreviewActivity.startPreview(context, images = it)
        }
//        context.startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(Uri.parse(item.imagePath), "image/*").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
    }

    private fun startApp(packageName:String) {
        if (packageName.startsWith("http")) {
            AppJumpUtils.startWebLink(context = SystemUtils.getApplicationContext(), url = packageName)
            return
        }
        SystemUtils.getApplicationContext().packageManager?.getLaunchIntentForPackage(packageName)?.let {
            SystemUtils.getApplicationContext().startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }
}